package com.demo.base.advice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.demo.base.exception.ParamException;
import com.demo.base.resp.ResufulResult;
@RestControllerAdvice
public class GolableExceptionHandler {

	public static final String ERROR_VIEW = "/error/my_error";

	@ExceptionHandler(value = Exception.class)
	public Object exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
		e.printStackTrace();
		if (isAjax(request)) {// 是ajax请求
			if (e instanceof ParamException) {
				return ResufulResult.fail(e.getMessage());
			}
			return ResufulResult.fail("未知错误");
		} else {// 不是ajax请求
			ModelAndView mv = new ModelAndView();
			mv.addObject("exception", e);
			mv.addObject("url", request.getRequestURL());// 发生异常的路径
			mv.setViewName(ERROR_VIEW);// 指定发生异常之后跳转页面
			return mv;
		}
	}

	private boolean isAjax(HttpServletRequest request) {// 判断request是否是ajax请求
		return (request.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
	}
}